package serial.utils;


import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class SerialPort {
    private static final String TAG = "SerialPort";

    /*
     * Do not remove or rename the field mFd: it is used by native method
     * close();
     */
    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;

    public SerialPort(){
    }


    public SerialPort(File device, int baudrate, int nBits, char nEvent,
                      int nStop, int flags) throws SecurityException, IOException {
        /* Check access permission */
        checkPermission(device);

        mFd = open(device.getAbsolutePath(), baudrate, nBits, nEvent, nStop, flags);
        if (mFd == null) {
//            Log.e(TAG, "native open returns null");
            throw new IOException("native open returns null");
        }


        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

    /**
     * 检查串口读写权限
     * @param device
     * @throws SecurityException
     */
    private void checkPermission(File device) throws SecurityException {
        if (!device.canRead() || !device.canWrite()) {
            try {
				/**
				 Missing read/write permission, trying to chmod the file
				*/
                Process su;
                su = Runtime.getRuntime().exec("/system/bin/su");
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
                        + "exit\n";
                su.getOutputStream().write(cmd.getBytes());
                if ((su.waitFor() != 0) || !device.canRead()
                        || !device.canWrite()) {
                    throw new SecurityException(cmd+" open returns null");
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new SecurityException("open returns null");
            }

        }
    }


    /**
     * 打开串口
     * @throws IOException 串口打开异常
     */
    public FileDescriptor open(File device, int baudrate, int nBits, char nEvent,
                               int nStop, int flags) throws IOException{
        checkPermission(device);
        FileDescriptor fd = open(device.getAbsolutePath(), baudrate, nBits, nEvent, nStop, flags);
        if (fd == null) {
//            Log.e(TAG, "native open returns null");
            throw new IOException("native open returns null");
        }
        return fd;
    }


    public boolean isOpen(FileDescriptor fd){
        return fd != null;
    }

    public FileDescriptor getFileDescriptor() {
        return mFd;
    }

    // Getters and setters
    public InputStream getInputStream() {
        return mFileInputStream;
    }

    public OutputStream getOutputStream() {
        return mFileOutputStream;
    }



    // JNI
    private native static FileDescriptor open(
            String path,
            int baudrate,    //波特率
            int nBits,        //数据位
            char nVerify,    //偶校验位
            int nStop,        //停止位
            int flags);

    public native void close();

    public native static int SetIoState(int control);

    public native static int GetPlatform();

    static {
        System.loadLibrary("serial_port");
    }

}